// SerialWorker.cpp
#include "serialportworker.h"
#include "mainview.h"
SerialWorker::SerialWorker(QObject *parent) : QObject(parent)
{

    // 初始化定时器，用于检查串口状态
        serialCheckTimer = new QTimer(this);
        connect(serialCheckTimer, &QTimer::timeout, this, &SerialWorker::checkSerialPort1);
        serialCheckTimer->start(1300);  // 每秒检查一次串口状态
}

void SerialWorker::start(QSerialPort *port)
{
    serialPort = port;
//    connect(serialPort, &QSerialPort::readyRead, this, &SerialWorker::readData);

}


void SerialWorker::updateBtnOnOff(bool state)
{
    btn_on_off = state;
}

void SerialWorker::checkSerialPort1()
{
//    static int a = 0;
//    qDebug() << "线程还没噶："<<a<<" 次";
//    a++;

    if (serialPort && !serialPort->isOpen()&&btn_on_off) {
        qDebug() << "串口意外关闭，尝试重新打开...";
        if (!serialPort->open(QIODevice::ReadWrite)) {
            qDebug() << "错误，串口无法重新打开，可能被占用！";
            // 这里可以增加重试逻辑或通知主线程处理
        } else {
            qDebug() << "串口重新打开成功。";
        }
    }
}


